package com.gopay.bis.bos.ebank.operation;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BosConstants;
import com.gopay.common.domain.bank.bos.ebank.BosB2cMessage;
import com.gopay.common.domain.bank.bos.ebank.query.BosB2cQueryRes;
import com.gopay.common.util.HttpTransport;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class BosB2cTransFormQuery {
	private BosB2cCertHelper bosB2cCerthelper;  
	
	private static Log logger = LogFactory.getLog(BosB2cTransFormQuery.class);
	
	/** 请求银行测试环境地址httpclient */
	//private BosHttpTransport bosHttpTransport;
	private HttpTransport httpTransport;
	
	 /* 上海银行B2C订单查询
	 * 
	 * @param BosB2cMessage 上海银行数据结构体.
	 * @return BosB2cMessage 上海银行数据结构体.
	 * @throws Exception
	 */
	public BosB2cMessage query(BosB2cMessage message) {
		BosB2cMessage retQueryMsg = new BosB2cMessage(); // 订单查询返回对象
		retQueryMsg.setOutStlmCd(BankConstants.BANK_LOGO_BOS);
		String[] signArray = null; // 签名信息
		boolean verifyRes; // 验签结果
		try {
			// 签名
			signArray = bosB2cCerthelper.signReturnArray(message);
		} catch (Exception e) {
		}

		// 设置发送参数
		Map<String, String> param = new HashMap<String, String>();
		param.put("merchantID", message.getMerchantID());
		param.put("orderList", message.getOrderList());
		param.put("orderBeginDate", message.getOrderBeginDate());
		param.put("orderEndDate", message.getOrderEndDate());
		param.put("notifyURL", message.getNotifyURL());
		param.put("signDataStr", message.getSignDataStr());
		param.put("signData", signArray[0]);
		param.put("KoalB64Cert", signArray[1]);
		BankLogUtils.printB2CQuerySendLog(retQueryMsg, param);
		// 发送参数
		httpTransport.setUrl(message.getQueryUrl());
		Object issueRes = null;
		try {
			issueRes = httpTransport.submit(param);
		} catch (Exception e) {
			return null;
		}
		BankLogUtils.printB2CQueryBlackLog(retQueryMsg, issueRes);
		BosB2cQueryRes returnMeassage = new BosB2cQueryRes();
		// 如果返回参数不为空则返回
		if (issueRes != null) {
			String resStr = (String)issueRes;

			// 将XML转换为对象
			XStream xs = new XStream(new DomDriver());
			xs.autodetectAnnotations(true);
			xs.toXML(returnMeassage);
			returnMeassage = (BosB2cQueryRes) xs.fromXML(resStr);

			if (!StringUtils.equals(returnMeassage.getRetCode(), BosConstants.ORDER_RET_CODE_SUCCESS)) {
				// 查询失败直接返回
				retQueryMsg.setRetCode(returnMeassage.getRetCode());
				retQueryMsg.setErrMsg(returnMeassage.getErrMsg());
				return retQueryMsg;
			}
			try {
				// 签名源数据
				String signDataStr = returnMeassage.getOpResult().getSignDataStr();
				
				// 签名信息
				String signData = returnMeassage.getOpResult().getSignData();
				
				// 重新组装签名源数据
				String plainStr = buildVerifyQuery(returnMeassage);
				message.setSignDataStr(plainStr);
				message.setSignData(signData);
				// 验签
				verifyRes = (Boolean)bosB2cCerthelper.verify(message);
			} catch (Exception e) {
				return null;
			}
			logger.error("bos b2c query verifyResult:"+verifyRes);
			if (verifyRes) {
				// 验签成功
				retQueryMsg = parseB2C(returnMeassage.getOpResult().getOrderListResult());
				retQueryMsg.setRetCode(returnMeassage.getRetCode());
				retQueryMsg.setErrMsg(returnMeassage.getErrMsg());
				
				logger.error("bos b2c query return msg:"+ToStringBuilder.reflectionToString(retQueryMsg));
				return retQueryMsg;
			} else {
				// 验签失败
				return null;
			}
		} else {
			return null;
		}
	}
	
	/**
	 * 组装对账验签明文
	 * @param returnMeassage
	 * @return
	 */
	public String buildVerifyQuery(BosB2cQueryRes returnMeassage){
		String merchartId=returnMeassage.getOpResult().getMerchantID();
		String orderListResult=returnMeassage.getOpResult().getOrderListResult();
		StringBuffer sb = new StringBuffer("");
		sb.append(merchartId).append("|")
		.append(orderListResult);
		return sb.toString();
	}

	/**
	 * 解析上海银行B2C网关返回字段.
	 * 
	 * @param resStr
	 *            网关输出字段字符串.
	 * @return B2C数据结构体.
	 */
	public BosB2cMessage parseB2C(String resStr) {
		// 根据分隔符拆分出各个返回参数
		String[] reqParameters = resStr.split("\\|");
		// 获取每个参数
		BosB2cMessage msg = new BosB2cMessage();
		msg.setOutStlmCd(BankConstants.BANK_LOGO_BOS);
		msg.setMerOrderNum(reqParameters[0]);// 订单号
		msg.setOrdersResults(reqParameters[1]);// 订单结果
		msg.setMerOrderAmt(reqParameters[2]);// 交易金额
		if(reqParameters.length==4){
		    msg.setComment(reqParameters[3]);// 订单失败原因
		}else{
			msg.setComment("");
		}
		return msg;
	}

	

	/*public void setBosHttpTransport(BosHttpTransport bosHttpTransport) {
		this.bosHttpTransport = bosHttpTransport;
	}*/

	public void setBosB2cCerthelper(BosB2cCertHelper bosB2cCerthelper) {
		this.bosB2cCerthelper = bosB2cCerthelper;
	}

	public void setHttpTransport(HttpTransport httpTransport) {
		this.httpTransport = httpTransport;
	}
	

}
